<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Redis实现分布式锁 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Redis实现分布式锁要考虑的点 互斥(独占,只能有一个客户端获取锁) 不能死锁 容错(只要大部分 redis 节点创建了这把锁就认为成功获取到锁) 支持重入,超时获取锁等特性  redis实现分布式锁1.使用set1.1.加锁1SET key randomValue NX PX 30000 NX: (not exists)表示只有 key 不存在的时候才会设置成功.(如果此时 redis 中存在">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis实现分布式锁">
<meta property="og:url" content="https://flyingzc.github.io/articles/redis/redis10-lock.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="Redis实现分布式锁要考虑的点 互斥(独占,只能有一个客户端获取锁) 不能死锁 容错(只要大部分 redis 节点创建了这把锁就认为成功获取到锁) 支持重入,超时获取锁等特性  redis实现分布式锁1.使用set1.1.加锁1SET key randomValue NX PX 30000 NX: (not exists)表示只有 key 不存在的时候才会设置成功.(如果此时 redis 中存在">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2019-12-16T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.214Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Redis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Redis实现分布式锁",
  "url": "https://flyingzc.github.io/articles/redis/redis10-lock.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2019-12-16T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.214Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/redis/redis10-lock.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Redis实现分布式锁',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Redis实现分布式锁</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Redis实现分布式锁</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-12-16T16:00:00.000Z" title="发表于 2019-12-17 00:00:00">2019-12-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.214Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Redis/">Redis</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="Redis实现分布式锁"><a href="#Redis实现分布式锁" class="headerlink" title="Redis实现分布式锁"></a>Redis实现分布式锁</h1><h2 id="要考虑的点"><a href="#要考虑的点" class="headerlink" title="要考虑的点"></a>要考虑的点</h2><ol>
<li>互斥(独占,只能有一个客户端获取锁)</li>
<li>不能死锁</li>
<li>容错(只要大部分 redis 节点创建了这把锁就认为成功获取到锁)</li>
<li>支持重入,超时获取锁等特性</li>
</ol>
<h2 id="redis实现分布式锁"><a href="#redis实现分布式锁" class="headerlink" title="redis实现分布式锁"></a>redis实现分布式锁</h2><h3 id="1-使用set"><a href="#1-使用set" class="headerlink" title="1.使用set"></a>1.使用set</h3><h4 id="1-1-加锁"><a href="#1-1-加锁" class="headerlink" title="1.1.加锁"></a>1.1.加锁</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">SET key randomValue NX PX 30000<br></code></pre></td></tr></table></figure>
<p>NX: (not exists)表示只有 key 不存在的时候才会设置成功.(如果此时 redis 中存在这个 key,那么设置失败,返回 nil)<br>PX 30000: 30s 后 key 失效,意味着 30s 后锁自动释放.</p>
<p>随机数 randomValue 可以使用 时间戳 + 客户端编号 的方式 生成随机数.</p>
<h4 id="1-2-释放锁"><a href="#1-2-释放锁" class="headerlink" title="1.2.释放锁"></a>1.2.释放锁</h4><figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs lua"><span class="hljs-comment">-- 删除锁的时候,找到 key 对应的 value,跟自己传过去的 value 做比较,如果是一样的才删除.保证解的是自己加的锁</span><br><span class="hljs-keyword">if</span> redis.call(<span class="hljs-string">&quot;get&quot;</span>,KEYS[<span class="hljs-number">1</span>]) == ARGV[<span class="hljs-number">1</span>] <span class="hljs-keyword">then</span><br>    <span class="hljs-keyword">return</span> redis.call(<span class="hljs-string">&quot;del&quot;</span>, KEYS[<span class="hljs-number">1</span>])<br><span class="hljs-keyword">else</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br><span class="hljs-keyword">end</span><br></code></pre></td></tr></table></figure>

<p>如果 key 对应的 value 一致,则删除这个 key.</p>
<p>通过这个方式释放锁是为了避免 Client 释放了其他 Client 申请的锁.</p>
<h4 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h4><p>这种加的是单机的 redis 锁,会有单点故障问题.</p>
<p>1.单点故障<br>如果是 redis 单实例,那就是单点故障.</p>
<p>如果是 redis 主从架构,即使有 redis 主从异步复制.如果 master 节点挂了(key 就没有了),key 还没同步到 slave 节点,此时 slave 节点 切换为 master 节点,别人就可以 set key,从而拿到锁.</p>
<p>2.超时释放锁的问题<br>1.client A 获得锁成功<br>2.client B 等待 A 释放锁<br>3.client A 超时没释放锁(比如 full gc)<br>4.redis 删除掉 key,释放锁<br>5.client B 获得锁成功<br>6.client B 做修改操作<br>7.client A 恢复做修改操作,覆盖了 client B 的修改</p>
<h4 id="在上面基础上-加-乐观锁"><a href="#在上面基础上-加-乐观锁" class="headerlink" title="在上面基础上 加 乐观锁"></a>在上面基础上 加 乐观锁</h4><p>在lua脚本中,获取锁成功的同时,使用<code>redis.call(&quot;INCRBY&quot;, key, &quot;1&quot;)</code>返回一个单调递增的version.<br>这样假设 A 超时锁被 redis server 释放掉,此时 B 获得锁更新数据成功.A试图更新数据时判断A的版本号低于现在数据的版本号,则不允许A更改.</p>
<h3 id="2-RedLock-实现"><a href="#2-RedLock-实现" class="headerlink" title="2.RedLock 实现"></a>2.RedLock 实现</h3><h4 id="RedLock-原理"><a href="#RedLock-原理" class="headerlink" title="RedLock 原理"></a>RedLock 原理</h4><p>假设有 N 个 Redis master 节点,不考虑主从复制.<br>像在 Redis 单实例上一样获取 和 释放锁.<br>假设有 5 台 Redis 实例,这样同时宕机的概率很低.</p>
<p>获取锁流程:<br>1.获取当前时间</p>
<p>2.依次尝试从 5 个实例上,使用相同的 key 和 唯一的value 获取锁.<br>client 设置一个 网络连接 和 超时响应时间,远小于锁的失效时间.(这能避免 Redis 实例挂了,client 一直等待获得锁的响应).<br>若 server 没有在规定时间内响应,client 应立即尝试去另外一个 Redis 实例上 请求获取锁.</p>
<p>3.client 使用 当前时间 减去 开始获取锁的时间(1中的时间),得到的就是 获取锁使用的时间.<code>当 过半 Redis 节点都获取到锁,且 使用的时间 小于 锁失效时间,锁才算获取成功.</code></p>
<p>4.若成功获取锁,key的失效时间 等于 有效时间 减去 获取锁使用的时间(3中得到的时间).</p>
<p>5.若获得锁失败(比如 没能在过半Redis实例上获得到锁 或 获得锁的时间已经超过了 有效时间),client需要在所有Redis实例上解锁(不管是否加锁了都解锁).</p>
<h4 id="Redisson-对-RedLock-的实现"><a href="#Redisson-对-RedLock-的实现" class="headerlink" title="Redisson 对 RedLock 的实现"></a>Redisson 对 RedLock 的实现</h4><ol>
<li><p>使用api</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">RLock</span> <span class="hljs-variable">redLock</span> <span class="hljs-operator">=</span> redissonClient.getLock(<span class="hljs-string">&quot;REDLOCK_KEY&quot;</span>);<br><span class="hljs-comment">// 加锁.500ms获取不到锁则认为获取锁失败.锁的失效时间是 10s</span><br><span class="hljs-type">boolean</span> <span class="hljs-variable">isLock</span> <span class="hljs-operator">=</span> redLock.tryLock(<span class="hljs-number">500</span>, <span class="hljs-number">10000</span>, TimeUnit.MILLISECONDS);<br><span class="hljs-comment">// 解锁</span><br>redLock.unlock();<br></code></pre></td></tr></table></figure>
</li>
<li><p>加锁时的lua逻辑</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// RedissonLock.tryLockInnerAsync()方法</span><br>&lt;T&gt; RFuture&lt;T&gt; <span class="hljs-title function_">tryLockInnerAsync</span><span class="hljs-params">(<span class="hljs-type">long</span> leaseTime, TimeUnit unit, <span class="hljs-type">long</span> threadId, RedisStrictCommand&lt;T&gt; command)</span> &#123;<br>    internalLockLeaseTime = unit.toMillis(leaseTime);<br><br>    <span class="hljs-keyword">return</span> commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,<br>                <span class="hljs-comment">// 1.若 加锁的key(hash)不存在</span><br>                <span class="hljs-string">&quot;if (redis.call(&#x27;exists&#x27;, KEYS[1]) == 0) then &quot;</span> +<br>                    <span class="hljs-comment">// 通过 hset key uuid+threadId 1 来加锁</span><br>                    <span class="hljs-string">&quot;redis.call(&#x27;hset&#x27;, KEYS[1], ARGV[2], 1); &quot;</span> +<br>                    <span class="hljs-comment">// 设置锁(hash)失效时间</span><br>                    <span class="hljs-string">&quot;redis.call(&#x27;pexpire&#x27;, KEYS[1], ARGV[1]); &quot;</span> +<br>                    <span class="hljs-string">&quot;return nil; &quot;</span> +<br>                <span class="hljs-string">&quot;end; &quot;</span> +<br>                <span class="hljs-comment">// 2.若 加锁的key(hash)存在 且 uuid+threadId 也存在</span><br>                <span class="hljs-string">&quot;if (redis.call(&#x27;hexists&#x27;, KEYS[1], ARGV[2]) == 1) then &quot;</span> +<br>                    <span class="hljs-comment">// 重入计数加1</span><br>                    <span class="hljs-string">&quot;redis.call(&#x27;hincrby&#x27;, KEYS[1], ARGV[2], 1); &quot;</span> +<br>                    <span class="hljs-comment">// 重新设置(hash)失效时间</span><br>                    <span class="hljs-string">&quot;redis.call(&#x27;pexpire&#x27;, KEYS[1], ARGV[1]); &quot;</span> +<br>                    <span class="hljs-string">&quot;return nil; &quot;</span> +<br>                <span class="hljs-string">&quot;end; &quot;</span> +<br>                <span class="hljs-comment">// 3.返回锁(hash)的失效时间</span><br>                <span class="hljs-string">&quot;return redis.call(&#x27;pttl&#x27;, KEYS[1]);&quot;</span>,<br>                <span class="hljs-comment">// KEYS[1]锁key, ARGV[1]锁失效时间, ARGV[2] uuid+threadId</span><br>                Collections.&lt;Object&gt;singletonList(getName()), internalLockLeaseTime, getLockName(threadId));<br>&#125;<br></code></pre></td></tr></table></figure>

<p>1.加锁的hash不存在.创建hash,通过给 hash 的 key(uuid+threadId) 设置 value 为1.返回 nil表示加锁成功.<br>2.加锁的hash存在 且 key 也存在,表示当前线程重入的情况,重入计数加1.<br>3.走到这表示获取锁失败,返回锁的失效时间.</p>
<ol start="3">
<li>解锁时的lua逻辑</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">protected</span> RFuture&lt;Boolean&gt; <span class="hljs-title function_">unlockInnerAsync</span><span class="hljs-params">(<span class="hljs-type">long</span> threadId)</span> &#123;<br>    <span class="hljs-keyword">return</span> commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,<br>            <span class="hljs-comment">// 若锁key不存在,说明锁已释放.直接执行 publish 命令 发布释放锁消息 并返回 1</span><br>            <span class="hljs-string">&quot;if (redis.call(&#x27;exists&#x27;, KEYS[1]) == 0) then &quot;</span> +<br>                <span class="hljs-comment">// 向channel(即redisson_lock__channel:&#123;lockName&#125;)发送一条消息</span><br>                <span class="hljs-string">&quot;redis.call(&#x27;publish&#x27;, KEYS[2], ARGV[1]); &quot;</span> +<br>                <span class="hljs-string">&quot;return 1; &quot;</span> +<br>            <span class="hljs-string">&quot;end;&quot;</span> +<br>            <span class="hljs-comment">// 下面都是锁key存在的情况</span><br>            <span class="hljs-comment">// 锁key存在但是 field(id+threadId) 不匹配,说明不是当前线程加的锁,不管,返回 nil</span><br>            <span class="hljs-string">&quot;if (redis.call(&#x27;hexists&#x27;, KEYS[1], ARGV[3]) == 0) then &quot;</span> +<br>                <span class="hljs-string">&quot;return nil;&quot;</span> +<br>            <span class="hljs-string">&quot;end; &quot;</span> +<br>            <span class="hljs-comment">// 若锁key存在 且 field(id+threadId) 匹配,说明就是当前线程加的锁,重入计数减 1</span><br>            <span class="hljs-string">&quot;local counter = redis.call(&#x27;hincrby&#x27;, KEYS[1], ARGV[3], -1); &quot;</span> +<br>            <span class="hljs-comment">// 重入计数减1后count&gt;0,说明没完全释放掉锁.重新设置失效时间,返回0</span><br>            <span class="hljs-string">&quot;if (counter &gt; 0) then &quot;</span> +<br>                <span class="hljs-string">&quot;redis.call(&#x27;pexpire&#x27;, KEYS[1], ARGV[2]); &quot;</span> +<br>                <span class="hljs-string">&quot;return 0; &quot;</span> +<br>            <span class="hljs-comment">// 重入计数减为0的情况,完全释放锁,删除key解锁,publish解锁消息,返回1</span><br>            <span class="hljs-string">&quot;else &quot;</span> +<br>                <span class="hljs-string">&quot;redis.call(&#x27;del&#x27;, KEYS[1]); &quot;</span> +<br>                <span class="hljs-string">&quot;redis.call(&#x27;publish&#x27;, KEYS[2], ARGV[1]); &quot;</span> +<br>                <span class="hljs-string">&quot;return 1; &quot;</span>+<br>            <span class="hljs-string">&quot;end; &quot;</span> +<br>            <span class="hljs-string">&quot;return nil;&quot;</span>,<br>            <span class="hljs-comment">// KEYS[1]锁key, KEYS[2] channelName, ARGV[1]解锁消息 值为0, ARGV[2]锁失效时间, ARGV[3] id+threadId</span><br>            Arrays.&lt;Object&gt;asList(getName(), getChannelName()), LockPubSub.unlockMessage, internalLockLeaseTime, getLockName(threadId));<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>1.若锁key不存在,说明锁已释放.直接执行 publish 命令 发布释放锁消息 并返回 1<br>2.锁key存在但是 field(id+threadId) 不匹配,说明不是当前线程加的锁,不管,返回 nil<br>3.若锁key存在 且 field(id+threadId) 匹配,说明就是当前线程加的锁,重入计数减 1<br>3.1.重入计数减1后count&gt;0,说明没完全释放掉锁.重新设置失效时间,返回0<br>3.2.重入计数减为0的情况,完全释放锁,删除key解锁,publish解锁消息,返回1</p>
<h1 id="see"><a href="#see" class="headerlink" title="@see"></a>@see</h1><p><a target="_blank" rel="noopener" href="https://github.com/redisson/redisson/wiki/Redisson%E9%A1%B9%E7%9B%AE%E4%BB%8B%E7%BB%8D">Redisson项目官方介绍wiki</a></p>
<p><a target="_blank" rel="noopener" href="http://www.redis.cn/topics/distlock.html">Redis实现分布式锁官网</a></p>
<p><a target="_blank" rel="noopener" href="https://github.com/redisson/redisson/wiki/8.-%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%92%8C%E5%90%8C%E6%AD%A5%E5%99%A8#81-%E5%8F%AF%E9%87%8D%E5%85%A5%E9%94%81reentrant-lock">Redisson实现分布式锁官方wiki</a></p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/redis/redis10-lock.html">https://flyingzc.github.io/articles/redis/redis10-lock.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Redis/">Redis</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Redis%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-number">1.</span> <span class="toc-text">Redis实现分布式锁</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A6%81%E8%80%83%E8%99%91%E7%9A%84%E7%82%B9"><span class="toc-number">1.1.</span> <span class="toc-text">要考虑的点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#redis%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-number">1.2.</span> <span class="toc-text">redis实现分布式锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BD%BF%E7%94%A8set"><span class="toc-number">1.2.1.</span> <span class="toc-text">1.使用set</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-%E5%8A%A0%E9%94%81"><span class="toc-number">1.2.1.1.</span> <span class="toc-text">1.1.加锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-%E9%87%8A%E6%94%BE%E9%94%81"><span class="toc-number">1.2.1.2.</span> <span class="toc-text">1.2.释放锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.1.3.</span> <span class="toc-text">问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9C%A8%E4%B8%8A%E9%9D%A2%E5%9F%BA%E7%A1%80%E4%B8%8A-%E5%8A%A0-%E4%B9%90%E8%A7%82%E9%94%81"><span class="toc-number">1.2.1.4.</span> <span class="toc-text">在上面基础上 加 乐观锁</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-RedLock-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.2.2.</span> <span class="toc-text">2.RedLock 实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#RedLock-%E5%8E%9F%E7%90%86"><span class="toc-number">1.2.2.1.</span> <span class="toc-text">RedLock 原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Redisson-%E5%AF%B9-RedLock-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.2.2.2.</span> <span class="toc-text">Redisson 对 RedLock 的实现</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#see"><span class="toc-number">2.</span> <span class="toc-text">@see</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>